package com.df.my_net_game.game_rpc.client;

import com.df.my_net_game.game_rpc.client.annotation.GRpc;
import com.df.my_net_game.game_rpc.config.GRpcClientFactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.util.*;

public class GRpcScanner extends ClassPathBeanDefinitionScanner {
    ResourceLoader resourceLoader = null;
    public GRpcScanner(BeanDefinitionRegistry registry,ResourceLoader resourceLoader) {
        super(registry);
        this.resourceLoader = resourceLoader;
        this.addIncludeFilter(new AnnotationTypeFilter(GRpc.class));
    }

    public void scan(List<String> packages){
        String[] array = packages.toArray(new String[packages.size()]);
//        Set<BeanDefinitionHolder> beanDefinitions = super.doScan(array);
        for (String aPackage : packages) {
            Set<BeanDefinition> candidateComponents = super.findCandidateComponents(aPackage);
            System.out.println(1);
        }

//        if (beanDefinitions.isEmpty()) {
//            this.logger.warn("No @GRpc was found in '" + Arrays.toString(array) + "' package. Please check your configuration.");
//        } else {
//            this.processBeanDefinitions(beanDefinitions);
//        }
    }

    private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
        Iterator iterator = beanDefinitions.iterator();

        while(iterator.hasNext()) {
            BeanDefinitionHolder holder = (BeanDefinitionHolder)iterator.next();
            GenericBeanDefinition definition = (GenericBeanDefinition)holder.getBeanDefinition();
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Creating @GRpcBean with name '" + holder.getBeanName() + "' and '" + definition.getBeanClassName() + "' Interface");
            }

            definition.getConstructorArgumentValues().addGenericArgumentValue(Objects.requireNonNull(definition.getBeanClassName()));
            definition.setBeanClass(GRpcClientFactoryBean.class);
        }
    }
}
